import pandas as pd
import numpy as np
from utils.metrics import cal_csv_mAP

def str2np(x):
    return np.array(x.split(';')).astype(np.float)
label_map = {'n':0.000, 'm':0.000, 'y':0.99999}
def label2np(labels):
    return np.array([label_map[s] for s in labels]).astype(np.float)
def np2str(arr):
    return ';'.join(['%.4f'%x for x in arr])


results_test = pd.read_csv("online_pred1b/csv/test-merge2-98686.csv",sep=",",header=None,names=['ImageName', 'AttrKey', 'AttrValueProbs'])
print(results_test.keys())
skirt = pd.read_csv("online_pred1b/skirt_test_out.csv",sep=",",header=None,names=['ImageName', 'AttrKey', 'AttrValues'])
print(len(results_test))
outcsv = pd.merge(skirt, results_test, on=['ImageName','AttrKey'], how="left")
print(len(outcsv))
outcsv['AttrValueProbs'] =  outcsv['AttrValues'].apply(label2np)
val_mAP,APs, accs = cal_csv_mAP(outcsv,outcsv,['skirt_length_labels'])
outcsv['AttrValueProbs'] = outcsv['AttrValueProbs'].apply(np2str)
print(outcsv.head())
outcsv2 =outcsv[['ImageName', 'AttrKey', 'AttrValueProbs']]

# print results_test
# print outcsv2

print outcsv2.info()
print results_test.info()
final = pd.merge(results_test, outcsv2, on=['ImageName', 'AttrKey'], how='left')
print final['AttrKey'].value_counts()
final.loc[(final['AttrKey'] == 'skirt_length_labels')
          & (final['AttrValueProbs_y'].notnull()), 'AttrValueProbs_x'] = \
    final.loc[(final['AttrKey'] == 'skirt_length_labels')
          & (final['AttrValueProbs_y'].notnull()), 'AttrValueProbs_y']

print final[(final['AttrKey'] == 'skirt_length_labels')
          & (final['AttrValueProbs_y'].notnull())]

final['AttrValueProbs'] = final['AttrValueProbs_x']
final = final.drop(['AttrValueProbs_x','AttrValueProbs_y'],axis=1)
print final.info()
print final.head()
print final[(final['AttrKey'] == 'skirt_length_labels')]


final[['ImageName', 'AttrKey', 'AttrValueProbs']].to_csv('online_pred1b/csv/test-merge2-98686_replace1.csv', header=None, index=False)
